const app = getApp();
const https = require('../../utils/https.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    invoiceType: ['普通发票', '增值税专用发票'],
    invoiceTitle: ['个人', '公司'],
    disabled: false,
    loading: false,
    show_price: 0,
    type_name: '普通发票',
    title_type: '个人',
    use_integral: 0.00,
    is_invoice: 0,
    invoiceName: '',
    invoice: [],
    title_name: '',
    invoiceTel: '',
    choose_integral_txt: '选择使用魔法币',
    use_coupon_text: '请选择优惠券'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this,
      login_status = wx.getStorageSync('login_status');
    if (!login_status || login_status <= 0) {
      wx.showLoading({
        title: '请先进行登陆',
      })
      setTimeout(() => {
        wx.hideLoading({
          success: (res) => {
            wx.navigateTo({
              url: '/pages/grant/grant',
            })
          },
        })
      }, 1500);
    } else {
      that.getUserInfo();
      that.getInfo();
    }
  },
  getUserInfo: function () {
    var that = this,
      user_id = wx.getStorageSync('user_id');
    https.post('getUserInfo', {
      user_id: user_id
    }, true).then(res => {
      that.setData({
        integral: res.integral
      })
    })
  },
  /**
   * @xk 获取订单信息
   */
  getInfo: function () {
    var that = this,
      user_id = wx.getStorageSync('user_id'),
      address_id = app.globalData.address_id,
      user_coupon_id = app.globalData.user_coupon_id,
      use_integral = app.globalData.use_integral,
      choose_integral_txt = this.data.choose_integral_txt,
      cart_ids = app.globalData.cart_id;
    https.post('getMakeSure', {
      cart_ids: cart_ids,
      user_id: user_id,
      address_id: address_id,
      user_coupon_id: user_coupon_id
    }, true, '等待加载中').then(res => {
      if (res.address) {
        app.globalData.address_id = res.address.id;
      }
      if (res.coupon) {
        app.globalData.user_coupon_id = res.coupon.id;
      }
      if (use_integral > 0) {
        var use_money = use_integral * res.integral_to_money;
        if (res.all_price > use_money) {
          var show_price = res.all_price - use_money;
        } else {
          use_integral = res.all_price/res.integral_to_money;
          show_price = 0;
        }
        choose_integral_txt = "选择使用" + use_integral + "积分抵扣" + use_integral * res.integral_to_money;
      }else{
        if(res.all_max_integral > 0){
          choose_integral_txt = "当前可用"+res.all_max_integral+"个魔法币，点击使用";
        }else{
          choose_integral_txt = "不允许使用魔法币";
        }
      }
      that.setData({
        cart_list: res.cart_list,
        total: res.total_price,
        integral_to_money: res.integral_to_money,
        all_price: res.all_price - use_integral * res.integral_to_money,
        show_price: res.all_price - use_integral * res.integral_to_money,
        address: res.address,
        all_max_integral: res.all_max_integral,
        cost_price: res.cost_price,
        coupon_price: res.coupon_price,
        user_coupon: res.user_coupon,
        use_integral: use_integral,
        use_coupon_text: res.use_coupon_text,
        choose_integral_txt: choose_integral_txt
      })
      if (res.is_can_pay == 0) {
        wx.showToast({
          title: res.is_not_pay_msg,
          icon: 'none',
          duration: 1500
        })
        that.setData({
          loading: false,
          disabled: true
        })
      }

    })
  },
  /**
   * @xk 更改收货地址
   */
  chanageAddress: function () {
    this.setData({
      loading: false,
      disabled: false
    })
    app.globalData.use_integral = this.data.use_integral;
    wx.navigateTo({
      url: '/pages/address_edit/edit',
    })
  },
  // 选择优惠券
  chooseCoupon: function () {
    app.globalData.use_integral = this.data.use_integral;
    wx.navigateTo({
      url: '/pages/my_coupon/coupon',
    })
  },
  //改变发票类型
  typeChooise(e) {
    this.setData({
      type_name: e.currentTarget.dataset.type_name
    })
  },
  //改变抬头类型
  titleChooise(e) {
    this.setData({
      title_type: e.currentTarget.dataset.title_type
    })
  },
  // 开发票
  invoiceTap() {
    this.setData({
      maskShow: true,
      invoiceShow: true
    })
  },
  chanageTitleName(obj) {
    this.setData({
      title_name: obj.detail.value
    })
  },
  chanageName(obj) {
    this.setData({
      invoiceName: obj.detail.value
    })
  },
  chanageTel(obj) {
    this.setData({
      invoiceTel: obj.detail.value
    })
  },
  // 确认使用发票
  practical() {
    var that = this,
      invoiceName = this.data.invoiceName,
      invoiceTel = this.data.invoiceTel,
      title_name = this.data.title_name,
      title_type = this.data.title_type,
      type_name = this.data.type_name;
    if (title_name == '' || !title_name) {
      wx.showToast({
        title: '请填写发票抬头',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (invoiceName == '' || !invoiceName) {
      wx.showToast({
        title: '请填写收票人名称',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (invoiceTel == '' || !invoiceTel) {
      wx.showToast({
        title: '请填写收票人电话',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    var invoice = ({
      type_name: type_name,
      title_type: title_type,
      title_name: title_name,
      invoiceName: invoiceName,
      invoiceTel: invoiceTel
    });
    app.globalData.invoice = invoice;
    // console.log(invoice);
    this.setData({
      maskShow: false,
      is_invoice: 1,
      invoice: invoice,
      invoiceShow: false
    })
  },
  // 不使用发票
  notinvoice() {
    this.setData({
      maskShow: false,
      invoiceShow: false,
      magicShow: false,
      type_name: '普通发票',
      title_type: '个人',
      is_invoice: 0,
      invoiceName: '',
      title_name: '',
      invoiceTel: '',
    })
  },
  // 使用魔法币
  magicTap() {
    this.setData({
      maskShow: true,
      magicShow: true
    })
  },
  // 魔法币使用
  chanageIntegral(obj) {
    this.setData({
      use_integral: obj.detail.value
    })
  },
  //不适用魔法币
  notpractical() {
    var all_price = this.data.all_price;
    this.setData({
      use_integral: 0.00,
      choose_integral_txt: '暂不使用魔法币',
      maskShow: false,
      show_price: all_price,
      invoiceShow: false,
      magicShow: false
    })
  },
  //使用魔法币
  useIntegral() {
    var that = this,
      use_integral = this.data.use_integral,
      all_max_integral = this.data.all_max_integral,
      all_price = this.data.all_price,
      integral_to_money = this.data.integral_to_money,
      has_integral = this.data.integral;
    if (has_integral > use_integral && use_integral <= all_max_integral) {
      //开始判断是否还存在可以使用的魔法币
      var use_money = use_integral * integral_to_money;
      if (all_price > use_money) {
        var show_price = all_price - use_money;
      } else {
        use_integral = all_price;
        show_price = 0;
      }
      //如果当前积分足够，并且使用积分满足最大允许的积分
      this.setData({
        chooiseColor: true,
        choose_integral_txt: '选择使用' + use_integral + '积分抵扣' + use_integral * integral_to_money,
        maskShow: false,
        show_price: show_price,
        magicShow: false
      })
    } else {
      wx.showToast({
        title: '请在规则范围内使用积分',
        icon: 'none',
        duration: 1500
      })
    }

  },
  /**
   * @xk 提交订单
   *  
   */
  submit: function (res) {
    var that = this,
      invoice = this.data.invoice,
      cart_ids = app.globalData.cart_id,
      address_id = app.globalData.address_id,
      user_coupon_id = app.globalData.user_coupon_id,
      is_invoice = this.data.is_invoice,
      use_integral = this.data.use_integral,
      user_id = wx.getStorageSync('user_id');
    this.setData({
      loading: true,
      disabled: true
    })
    https.post('saveOrder', {
      invoice: invoice,
      cart_ids: cart_ids,
      address_id: address_id,
      user_coupon_id: user_coupon_id,
      use_integral: use_integral,
      user_id: user_id,
      is_invoice: is_invoice
    }, false, '正在提交').then(res => {
      app.globalData.cart_id = '';
      app.globalData.address_id = 0;
      app.globalData.user_coupon_id = 0;
      app.globalData.use_integral = 0;
      app.globalData.order_sn = res.order_sn;
      if (res.code == 205) {
        //执行微信支付
        wx.requestPayment({
          timeStamp: res.pay_info.timeStamp,
          nonceStr: res.pay_info.nonceStr,
          package: res.pay_info.package,
          signType: res.pay_info.signType,
          paySign: res.pay_info.paySign,
          success(res) {
            if (res.errMsg == 'requestPayment:ok') {
              wx.showToast({
                title: '支付成功',
                icon: 'none',
                duration: 1500
              })
              wx.redirectTo({
                url: '/pages/pay_success/success',
              })
            } else {
              wx.showToast({
                title: '支付取消',
                icon: 'none',
                duration: 2000
              })
              wx.redirectTo({
                url: '/pages/my_order/my_order',
              })
            }
          },
          fail(res) {
            wx.showToast({
              title: '支付取消 ',
              icon: 'none',
              duration: 1500
            })
            wx.redirectTo({
              url: '/pages/my_order/my_order',
            })
          }
        })
      } else {
        wx.redirectTo({
          url: '/pages/pay_success/success',
        })
      }


    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onShow();
  },
})